<template>
  <div id="admin">
    <div class="titleBar">
      <div>菜单管理</div>
      <div>
        <el-button
          type="primary"
          @click="(dialogVisible = true), (isAdd = true)"
          >新增菜单</el-button
        >
      </div>
    </div>
    <div class="tabBar">
      <div></div>
      <div>
        <el-table
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="menu_id"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="index" width="50" fixed align="center">
          </el-table-column>
          <el-table-column
            prop="title"
            label="菜单名称"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column label="图标" width="70" align="center">
            <template slot-scope="scope">
              <span
                class="icon-picker-selected"
                v-if="scope.row.meta.icon !== '' && scope.row.meta.icon != null"
              >
                <i :class="scope.row.meta.icon"></i>
              </span>
              <!-- <svg-icon
                style="width: 15px; heigth: 15px"
                :icon-class="scope.row.meta.icon"
              /> -->
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="页面名称"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column label="菜单级别" width="100" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" effect="dark" v-if="scope.row.level == 1"
                >顶级菜单</el-tag
              >
              <el-tag size="mini" v-if="scope.row.level == 2">一级菜单</el-tag>
              <el-tag size="mini" effect="plain" v-if="scope.row.level == 3"
                >二级菜单</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="component"
            label="组件"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="redirect"
            label="重定向"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="path" label="路径" align="center">
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
          </el-table-column>
          <el-table-column label="是否启用" width="120" align="center">
            <template slot-scope="scope">
              <el-switch
                @change="switchMenu(scope.row)"
                v-model="scope.row.status"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="操作"
            width="130"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="primary"
                icon="el-icon-edit"
                circle
                size="small"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="small"
                @click="deleteMenu(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表单 -->
    <el-dialog
      :title="isAdd ? '新增菜单' : '修改菜单'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-form"
      >
        <el-form-item label="菜单名称(title)" prop="title">
          <el-input size="mini" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input size="mini" v-model="form.component"></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input size="mini" v-model="form.path"></el-input>
        </el-form-item>
        <el-form-item label="页面名称(name)" prop="name">
          <el-input size="mini" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="重定向" prop="redirect">
          <el-input size="mini" v-model="form.redirect"></el-input>
        </el-form-item>
        <el-form-item label="子菜单" prop="parent_id">
          <div class="block">
            <el-cascader
              v-model="levels"
              :key="cascaderKey"
              :options="options"
              :props="{ checkStrictly: true }"
              @change="select"
              clearable
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <selectIcon :value="form.icon" @change="changeIcon"></selectIcon>
        </el-form-item>
        <el-form-item label="是否隐藏">
          <el-switch
            v-model="form.hidden"
            active-color="#13ce66"
            inactive-color="#ff4949"
            dd="ss"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            prop="status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否为菜单">
          <el-switch
            v-model="form.menu_type"
            active-value="M"
            inactive-value="F"
            active-color="#13ce66"
            inactive-color="#ff4949"
            prop="aa"
          ></el-switch>
        </el-form-item>
        <el-form-item label="菜单排序">
          <el-input-number
            size="mini"
            style="width: 100%"
            v-model="form.order_num"
            controls-position="right"
            :min="1"
            prop="menu"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="addMenu('form', form)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteMenu,
  getUseMenuList,
  addMenu,
  updateMenu,
  getAllmenu1,
} from "@/api/menuManagement";
import selectIcon from "@/components/selectIcon/index";
import { status } from "nprogress";
export default {
  watch: {
    //报错
    options(val) {
      // console.log(val);
      this.cascaderKey++;
    },
  },

  data() {
    return {
      form: {
        title: "",
        component: "",
        path: "",
        name: "",
        redirect: "",
        parent_id: "",
        hidden: "",
        icon: "",
        status: "",
        menu_type: "",
        order_num: "",
        level: "",
        levels: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入菜单名称(title)", trigger: "blur" },
        ],
        component: [
          { required: true, message: "请输入组件名称", trigger: "blur" },
        ],
        // path: [
        //   {
        //     required: true,
        //     message: "请输入路径",
        //     trigger: "blur",
        //   },
        // ],

        // name: [
        //   {
        //     required: true,
        //     message: "请输入页面名称(name)",
        //     trigger: "blur",
        //   },
        // ],
        // redirect: [
        //   {
        //     required: true,
        //     message: "请输入重定向",
        //     trigger: "blur",
        //   },
        // ],
        parent_id: [
          {
            required: true,
            message: "请选菜单层级或者该菜单的父级菜单",
            trigger: "change",
          },
        ],
        icon: [
          { required: true, message: "请选择菜单的图标", trigger: "change" },
        ],
      },
      cascaderKey: 1,
      options: [],
      isAdd: true,
      tableData: [],
      //弹窗
      dialogVisible: false,
      //子菜单回显
      levels: "",
    };
  },
  components: { selectIcon },

  created() {
    this.init();
  },

  methods: {
    init() {
      this.getUseMenuList();
    },

    //获取全部菜单
    getUseMenuList() {
      getAllmenu1().then((res) => {});
      getUseMenuList().then((res) => {
        this.tableData = res.data;
        let MenuTop = [
          {
            value: 0,
            label: "顶级菜单",
            children: [],
          },
        ];
        res.data.forEach((item) => {
          let child = {
            value: item.menu_id,
            label: item.meta.title,
            children: [],
          };
          if (item.children) {
            item.children.forEach((element) => {
              let grandson = {
                value: element.menu_id,
                label: element.meta.title,
              };
              child.children.push(grandson);
            });
          }
          MenuTop[0].children.push(child);
        });
        this.options = MenuTop;
      });
    },

    //新增菜单
    addMenu(form, data) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            addMenu(data).then((res) => {
              if (res.code == 0) {
                this.$refs.form.resetFields();
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          } else {
            updateMenu(data).then((res) => {
              if (res.code == 0) {
                this.$refs.form.resetFields();
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //删除菜单
    deleteMenu(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, "此操作将永久删除 "),
          h("i", { style: "color: teal" }, row.name),
          h("span", null, "菜单"),
          h(
            "span",
            { style: "color: #F56C6C" },
            "（如果该菜单有子菜单，将一同删除）"
          ),
          h("span", null, "，是否继续？"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMenu(row).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.init();
            } else {
              this.$message({
                type: "danger",
                message: "发生错误无法删除",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //关闭弹窗回调
    handleClose(done) {
      this.$confirm("你还未提交信息，确认关闭？")
        .then((_) => {
          this.$refs.form.resetFields();
          done();
        })
        .catch((_) => {});
    },

    //清空表单
    resetForm(form) {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
    },

    //编辑按钮
    handleClick(row) {
      this.levels = row.levels.split(",").map(Number);
      row.icon = row.meta.icon;
      this.isAdd = false;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.form = Object.assign({}, row);
      });
    },

    //选择图标
    changeIcon(data) {
      this.form.icon = data;
    },

    //是否启用
    change(row) {
      let data = row;
    },

    //
    select(data) {
      this.form.levels = data.join(",");
      this.form.level = data.length;
      this.form.parent_id = data.slice(-1)[0];
      // console.log(this.form.parent_id);
    },

    //启用菜单
    switchMenu(row) {
      let data = {
        menu_id: row.menu_id,
        status: row.status,
      };
      updateMenu(data).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.init();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#admin {
  height: calc(100vh - 84px);
  width: 100%;
  background-color: #ffffff;
  padding: 0 20px 20px 20px;
  line-height: auto;

  .titleBar {
    border-bottom: 1px solid #0000002e;
    height: 70px;
    line-height: 70px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .tabBar {
    height: calc(100vh - 174px);
    overflow: auto;

    .icon-picker-selected > i {
      font-size: 16px;
    }
  }
}

::v-deep .el-dialog {
  margin-top: 8vh !important;
  width: 35% !important;
  min-width: 450px !important;
}
</style>